package com.leyou.service;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.leyou.common.constants.SmsConstants;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.JsonUtils;
import com.leyou.config.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class SendSms {

    @Autowired
    private IAcsClient client;

    @Autowired
    private SmsProperties smsProperties;

    public void sendCheckCode(String phone, String code){

        log.info("【阿里云短信服务】发送短信验证码开始！");
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(smsProperties.getDomain());
        request.setVersion(smsProperties.getVersion());
        request.setAction(smsProperties.getAction());
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_REGION_ID, smsProperties.getRegionID());
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_PHONE,phone);
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_SIGN_NAME, smsProperties.getSignName());
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_TEMPLATE_CODE, smsProperties.getVerifyCodeTemplate());
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_TEMPLATE_PARAM, "{\"code\":\""+code+"\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            //拿到来自 运营商服务器的响应数据
            Map<String,String> map = JsonUtils.toMap(response.getData(), String.class, String.class);
            //判断 返回的消息是否是 code : ok
            if (StringUtils.equals(map.get(SmsConstants.SMS_RESPONSE_KEY_CODE),SmsConstants.OK)){
                log.info("【阿里云短信服务】发送短信验证码结束！");
            }else {
                log.error("【阿里云短信服务】发送短信验证码异常！异常信息为：{}", map.get(SmsConstants.SMS_RESPONSE_KEY_MESSAGE));
            }
        } catch (ServerException e) {
            //阿里的异常
            log.error("【阿里云短信服务】发送短信验证码阿里云服务器异常！");
            throw new LyException(ExceptionEnum.SEND_MESSAGE_ERROR);
        } catch (ClientException e) {
            //本地服务器的异常
            log.error("【阿里云短信服务】发送短信验证码本地服务器异常！");
            throw new LyException(ExceptionEnum.SEND_MESSAGE_ERROR);
        }
    }
}